<script setup>
import SendCaptcha from '@/components/user/SendCaptcha.vue'
import { ref, watch, computed } from 'vue'
import userApi from '@/apis/user'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { useConfigStore } from '@/stores/config'

const configStore = useConfigStore()
const resetTypes = computed(() => {
  let fields = []
  ;['email', 'mobile'].forEach((element) => {
    if (configStore.get(`user.${element}_feature`, []).includes('forget')) {
      fields.push(element)
    }
  })
  return fields
})
const activeTab = ref('')

const form = ref(null)
const rules = computed(() => {
  const result = {
    username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      //必须超过6个字符吗，并要求包含数字和字母
      {
        validator: (rule, value, callback) => {
          if (value.length < 6) {
            callback(new Error('密码必须超过6个字符'))
          } else if (!/[a-zA-Z]/.test(value) || !/[0-9]/.test(value)) {
            callback(new Error('密码必须包含数字和字母'))
          } else {
            callback()
          }
        },
      },
    ],
    confirmPassword: [
      { required: true, message: '请再次输入密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== model.value.password) {
            callback(new Error('两次输入密码不一致'))
          } else {
            callback()
          }
        },
      },
    ],
    captcha: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      //验证码格式为4个数字
      {
        validator: (rule, value, callback) => {
          if (value.length !== 4) {
            callback(new Error('验证码格式错误'))
          } else {
            callback()
          }
        },
      },
    ],
  }
  if (activeTab.value === 'email') {
    result.account = [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
            callback(new Error('邮箱格式错误'))
          } else {
            callback()
          }
        },
      },
    ]
  } else if (activeTab.value === 'mobile') {
    result.account = [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (!/^1[3456789]\d{9}$/.test(value)) {
            callback(new Error('手机号格式错误'))
          } else {
            callback()
          }
        },
      },
    ]
  }
  return result
})

const model = ref({
  username: '',
  password: '',
  confirmPassword: '',
  captcha: '',
})

const submitForm = async () => {
  const values = model.value
  await form.value.validate(async (valid) => {
    if (valid) {
      try {
        await userApi.passport.forget(activeTab.value, values)
      } catch (e) {
        console.log(e)
      }
    } else {
      return false
    }
  })
}

watch(
  resetTypes,
  (val) => {
    activeTab.value = val[0]
  },
  { immediate: true }
)

watch(
  activeTab,
  () => {
    model.value.captcha = ''
    model.value.account = ''
  },
  { immediate: true }
)
</script>

<template>
  <div class="text-center font-bold text-2xl">重置密码</div>
  <div class="forget-type flex-1 mt-5 space-y-5">
    <el-segmented
      v-if="resetTypes.length > 1"
      v-model="activeTab"
      :options="[
        { label: '通过邮箱重置', value: 'email' },
        { label: '通过手机号重置', value: 'mobile' },
      ]"
    />
    <el-form
      v-if="resetTypes.length > 0"
      :model="model"
      label-width="auto"
      :rules="rules"
      ref="form"
    >
      <el-form-item label="手机号" prop="account" v-if="activeTab === 'mobile'">
        <el-input v-model="model.account" placeholder="请输入已绑定手机号" />
      </el-form-item>
      <el-form-item label="验证码" prop="captcha" v-if="activeTab === 'mobile'">
        <el-input v-model="model.captcha" placeholder="请输入手机验证码">
          <template #append>
            <SendCaptcha type="mobile" :account="model.account" event="forget" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="account" v-if="activeTab === 'email'">
        <el-input v-model="model.account" placeholder="请输入已绑定邮箱" />
      </el-form-item>
      <el-form-item label="验证码" prop="captcha" v-if="activeTab === 'email'">
        <el-input v-model="model.captcha" placeholder="请输入邮箱验证码">
          <template #append>
            <SendCaptcha type="email" :account="model.account" event="forget" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input type="password" v-model="model.password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="model.confirmPassword" placeholder="请再次输入密码" />
      </el-form-item>
      <el-form-item label="&nbsp;">
        <el-button type="primary" @click="submitForm">
          <FontAwesomeIcon icon="sign-in-alt" />
          <span class="pl-1">重置密码</span>
        </el-button>
      </el-form-item>
    </el-form>
    <div v-else class="py-10 text-center text-[--el-text-color-primary]">
      <p class="mb-10 text-[--el-color-warning]">
        <FontAwesomeIcon icon="info-circle" size="4x" />
      </p>
      <p>抱歉，密码重置功能已关闭。</p>
    </div>
  </div>
</template>

<style scoped>
.forget-type .el-segmented {
  --el-segmented-item-selected-color: var(--el-text-color-primary);
  --el-segmented-item-selected-bg-color: var(--el-fill-color-darker);
  width: 100%;
  height: 2rem;
}
</style>
